
package com.oa.co.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @date 2023/5/6
 * @desc
 */
public class CrossInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("跨域拦截器配置");
        //解决跨域问题
        String origin = request.getHeader("Origin");


        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,Access-Token,token");
        response.setHeader("Access-Control-Expose-Headers", "*");//响应客户端的头部 允许携带Token 等等
        response.setHeader("Access-Control-Allow-Credentials", "true");  // 允许携带cookie
        response.setHeader("Access-Control-Max-Age", "3600");   // 预检请求的结果缓存时间


        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            //OPTIONS 请求 只是探路  不用请求真正的controller
            return false;
        }

        return true;
    }
}

